<?php
$csvfile = __DIR__ ."/../b_stocklist.csv";

$n_to_c = [];
$c_to_n = [];

// 原始数据
if (($handle = fopen($csvfile, "rb")) !== false) {
    while (($row = fgets($handle, 1000)) !== false) {
        // 删除单引号，双引号和*号
        $row = str_replace(['"',"'",'*'], '', $row);

        // 拆分成字段
        $row = explode(',', $row);
        
        // 代码，名称，拼音首字母
        list($c, $n, $p) = $row;
        
        // 剔除第一行
        if ($c === 'c') {
            continue;
        }

        $n_to_c[$n] = $c;
        $c_to_n[$c] = $n;
    }
    fclose($handle);
}

// PHP: n->c
$path = __DIR__ ."/n_to_c.php";
$content = var_export($n_to_c, true);
file_put_contents(
    $path,
    <<<TEXT
<?php
return $content;
TEXT
);

// PHP: c->n
$path = __DIR__ ."/c_to_n.php";
$content = var_export($c_to_n, true);
file_put_contents(
    $path,
    <<<TEXT
<?php
return $content;
TEXT
);

// JSON: n->c
$path = __DIR__ ."/n_to_c.json";
$content = json_encode($n_to_c, JSON_UNESCAPED_UNICODE);
file_put_contents(
    $path,
    <<<TEXT
$content
TEXT
);

// JSON: c->n
$path = __DIR__ ."/c_to_n.json";
$content = json_encode($c_to_n, JSON_UNESCAPED_UNICODE);
file_put_contents(
    $path,
    <<<TEXT
$content
TEXT
);
